package Algorithms.jishi.niuke.huawei.mianshi;

import lombok.Data;

import java.util.Objects;

/**
 * description: <br>
 * createTime: 2020/12/3 15:39 <br>
 *
 * @author zzh
 */
public class LastIndex {
    public static int getlastIndex (int total, int outIndex) {
        if(total < 0) {
            throw new IllegalArgumentException("total不能小于0");
        }
        if(total == 0) {
            return 0;
        }
        Node first = new Node();
        first.setIndex(1);
        Node current = first;
        Node prev = first;
        for (int i = 1; i < total; i++) {
            Node newNode = new Node();
            newNode.setIndex(i + 1);
            prev.setNext(newNode);
            newNode.setPrev(prev);
            prev = newNode;
        }
        first.setPrev(prev);
        prev.setNext(first);
        current = first;
        int count = 0;
        Node next = null;
        while(current.getNext() != current) {
            if(++count % outIndex == 0) {
                System.out.println(current.getIndex());
                prev = current.getPrev();
                next = current.getNext();
                prev.setNext(next);
                next.setPrev(prev);
                current = next;
            } else {
                current = current.getNext();
            }
        }
        return current.getIndex();
    }

    public static void main(String[] args) {
        System.out.println(getlastIndex(12, 3));
    }

    @Data
    static class Node {
        private Node prev;
        private Node next;
        private int index;


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Node)) return false;
            Node node = (Node) o;
            return index == node.index;
        }


        @Override
        public int hashCode() {
            return index;
        }
    }
}
